import PageTable from '@/components/q-table/component/page-table.vue';
import { OperationBtn, PageTableColumn, PageTableProps, SearchData } from '@/components/q-table/type';

type UsePageTableOptions<D> = {
	columns: PageTableColumn[];
	api?: (params: PaginationParams) => Promise<UniCloudGetData<D>>;
	success?: (data: D[]) => void;
	operations?: OperationBtn<D>[];
};
export const usePageTable = <D>(options: UsePageTableOptions<D>) => {
	const pageTableRef = ref<InstanceType<typeof PageTable>>();

	const realColumns = options.operations
		? [...(options.columns ?? []), { field: 'action', title: '操作', width: 100, slots: { default: 'action' } }]
		: options.columns;

	const columns = ref<PageTableProps['columns']>(realColumns);

	const operations = ref<OperationBtn<D>[]>(options.operations ?? []);

	const { message } = useFeedback(['message']);

	const tableRequest = async (data: SearchData) => {
		const fieldTypes =
			(columns.value as PageTableProps['columns'])
				?.filter((column) => column.searchFormItem)
				.map((column) => ({ key: column.field!, type: column.searchFormItem!.type })) ?? [];
		const query = getPaginationParams({
			data,
			fieldTypes,
			page: data.page,
			pageSize: data.pageSize,
		});

		if (options.api) {
			try {
				const res = await options.api(query);
				options.success?.(res.data);
				return { data: res.data, total: res.count };
			} catch (error: any) {
				message.error(error.message);
				console.log(error);
			}
		}
		return Promise.resolve({ data: [], total: 0 });
	};

	const getTableInstance = () => {
		return pageTableRef.value?.getTableInstance();
	};

	const getTableSearchInstance = () => {
		return pageTableRef.value?.getTableSearchInstance();
	};

	const refreshTable = (options?: { expand?: boolean }) => {
		pageTableRef.value?.refreshTable(options);
	};

	return { pageTableRef, columns, operations, tableRequest, getTableInstance, getTableSearchInstance, refreshTable };
};
